using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Rendering;
using TMPro;

public class PicPreview : MonoBehaviour
{
    public OpenFile openFile;
    public Camera renderCamera;
    public TextMeshProUGUI txtTitle;
    private List<string> imgPaths = new List<string>();
    private List<Image> items = new List<Image>();
    private RectTransform selfRectTran
    {
        get
        {
            if (_selfRectTran == null) _selfRectTran = GetComponent<RectTransform>();
            return _selfRectTran;
        }
    }
    private RectTransform _selfRectTran;
    private string savePath;

    public void AddFile()
    {
        string[] paths = openFile.OpenFileWin(true);
        if (paths == null) return;
        imgPaths.AddRange(paths);
        Refresh();
    }

    public void ClearFile()
    {
        imgPaths.Clear();
        Refresh();
    }

    public void CreateFile()
    {
        savePath = openFile.SaveFileWin();
    }


    public void Refresh()
    {
        foreach (var item in items)
        {
            if (item.sprite != null) Destroy(item.sprite.texture);
            Destroy(item.gameObject);
        }
        items.Clear();

        Resources.UnloadUnusedAssets();
        System.GC.Collect();

        for (int i = 0; i < imgPaths.Count; i++)
        {
            var item = new GameObject(i.ToString(), typeof(Image));
            var tran = item.transform;
            tran.SetParent(transform);
            tran.localPosition = Vector3.zero;
            tran.localEulerAngles = Vector3.zero;
            tran.localScale = Vector3.one;

            var img = item.GetComponent<Image>();
            items.Add(img);
            img.sprite = UIUtils.LoadByIO(imgPaths[i]);

            var rectTran = item.GetComponent<RectTransform>();
            if (img.sprite.texture.width > img.sprite.texture.height)
            {
                rectTran.sizeDelta = new Vector2(selfRectTran.sizeDelta.y, selfRectTran.sizeDelta.x / 4);
                rectTran.anchoredPosition = new Vector2(selfRectTran.sizeDelta.x / 4 * i + selfRectTran.sizeDelta.x / 8, selfRectTran.sizeDelta.y / 2);
                rectTran.anchoredPosition -= new Vector2(selfRectTran.sizeDelta.x / 2, selfRectTran.sizeDelta.y / 2);
                rectTran.localEulerAngles = new Vector3(0, 0, 90);
            }
            else
            {
                rectTran.sizeDelta = new Vector2(selfRectTran.sizeDelta.x / 4, selfRectTran.sizeDelta.y);
                rectTran.anchoredPosition = new Vector2(selfRectTran.sizeDelta.x / 4 * i + selfRectTran.sizeDelta.x / 8, selfRectTran.sizeDelta.y / 2);
                rectTran.anchoredPosition -= new Vector2(selfRectTran.sizeDelta.x / 2, selfRectTran.sizeDelta.y / 2);
            }
        }

        txtTitle.transform.SetAsLastSibling();
    }

    void Start()
    {
        RenderPipelineManager.endCameraRendering += OnPostRenderCallback;
    }

    void OnDestroy()
    {
        RenderPipelineManager.endCameraRendering -= OnPostRenderCallback;
    }


    void OnPostRenderCallback(ScriptableRenderContext renderContext, Camera camera)
    {
        if (string.IsNullOrEmpty(savePath) == false)
        {
            Vector2 leftBottom = selfRectTran.rect.min;
            Vector2 rightTop = selfRectTran.rect.max;
            Vector3 leftBottom_World = transform.TransformPoint(leftBottom);
            Vector3 rightTop_World = transform.TransformPoint(rightTop);
            Vector2 leftBottom_Screen = RectTransformUtility.WorldToScreenPoint(renderCamera, leftBottom_World);
            Vector2 rightTop_Screen = RectTransformUtility.WorldToScreenPoint(renderCamera, rightTop_World);
            Rect rect = new Rect(leftBottom_Screen, rightTop_Screen - leftBottom_Screen);
            Texture2D texture2D = UIUtils.ScreenShot_ReadPixels(rect);

            FileStream fileStream = new FileStream(savePath, FileMode.Create);
            fileStream.Write(texture2D.EncodeToPNG());
            fileStream.Close();
            fileStream.Dispose();
            fileStream = null;

            savePath = savePath.Replace('/', '\\');
            savePath = "/select," + savePath;
            System.Diagnostics.Process.Start("explorer.exe", savePath);

            savePath = string.Empty;
        }
    }
}
